package cn.ly.queue;

public class Queue<E> {
	private Object[] obj;
	private int size;
	private int front;
	private int rear;
	private int nItem;
	
	public Queue(int size){
		this.size = size;
		obj = new Object[size];
		front = 0;
		rear = -1;  //从队尾加入，-1+1=0
		nItem = 0;
	}
	
	public void insert(Object obj){
		if(rear == this.size-1){//用rear代表入队列指针，插入，需要判断插入指针是否指向了队尾，如果指向了队尾，需要把指针归位为-1,从头再做插入
			rear = -1;          
		}
		this.obj[++rear] = obj;//-1+1==>0
		nItem++;
		
	}
	
	public Object remove(){
		if(front == this.size){
			front = 0;
		}
		Object temp = this.obj[front++];//用front代表出队列指针，同时删除数据，需要判断指针是否指向了队尾，如果是，需要把指针归位为0，代表队列数据全部删除了，为空了
		nItem--;  //这可以控制队列有效数量，如果front到了队尾，nItem也就归0了
		return (E)temp;
	}
	
	public Object peek(){
		return this.obj[front];
	}
	
	public boolean isEmpty(){
		return nItem == 0;
	}
	
	public boolean isFull(){
		return nItem == size;
	}
	
	public int getItems(){
		return nItem;
	}
	
	public int size(){
		return this.size;
	}

}
